package com.eportal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.eportal.action.background.TLocksAction;
import com.eportal.aop.LogAnnotation;
import com.eportal.aop.WriteOperateLog;
import com.eportal.api.MdOpenApi;
import com.eportal.api.MdOpenBaseJson;
import com.eportal.base.BaseDAO;
import com.eportal.dao.*;
import com.eportal.domain.*;
import com.eportal.entity.*;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.params.background.TLocks.TLocksSendParam;
import com.eportal.params.background.TLocks.UpdateTlockParam;
import com.eportal.service.*;
import com.eportal.util.CityUtil;
import com.eportal.util.CommonUtil;
import com.eportal.util.Config;
import com.eportal.util.ValidateUtil;
import com.eportal.vo.controller.background.tlocks.*;
import com.framework.SpringContextHolder;
import com.framework.jqgrid.JqGridPager;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.*;


@Service("tLocksService")
public class TLocksServiceImpl extends BaseServiceImpl<TLocksEntity> implements TLocksService{

	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(TLocksServiceImpl.class.getName());

	@Autowired
	private TAgentService tAgentService;
	@Autowired
	private AppStoreService appStoreService;

	@Resource
	private TLocksHisOwnersEntityMapper tLocksHisOwnersDao;

	@Resource
	private TLocksEntityMapper tLocksDao;

    @Resource
    private TCommunityEntityMapper tCommunityDao;

    @Resource
    private TKeysEntityMapper tkeysDao;

    @Resource
    private TOpenlogEntityMapper tOpenlogDao;

    @Resource
    private TKeysProlongEntityMapper tKeysProlongDao;

    @Resource
    private TLocksInstalllogEntityMapper tLocksInstalllogDao;

	@Resource
	private AppStoreEntityMapper appStoreDao;

//	@Autowired
//    private TCommunityService tCommunityService;
	@Resource(name="dao")
	private BaseDAO dao;

	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }

	@Override
	public TLock get(Long sid){
		TLock tlocks = (TLock)dao.getById(TLock.class, sid);
		return tlocks;
	}

	public TLock getHql(String where) {
		 String hql = "from TLock where "+where;
	     return (TLock) dao.loadObject(hql);
	}

	public Object getObject(Class clazz,Long id) {
        return  dao.getById(clazz, id);
    }

    public Object getObject(String hql) {
		return  dao.loadObject(hql);
	}
    public List<Map<String, Object>> getPidToPid(String pidBegin,String pidEnd) {
//    	StringBuffer sql = new StringBuffer("select wm_concat(t.pid) as pids from t05_locks t where t.agtcode is null  and t.status ='-1' and t.pid>= '");
//		sql.append(pidBegin);
//		sql.append("' and t.pid <='");
//		sql.append(pidEnd);
//		sql.append("'");
		StringBuffer sql = new StringBuffer("select XMLAGG(XMLELEMENT(E, pid || ',')).EXTRACT('//text()').getclobval() as pids from T05_LOCKS t where t.agtcode is null  and t.status ='-1' and t.pid>= '");
		sql.append(pidBegin);
		sql.append("' and t.pid <='");
		sql.append(pidEnd);
		sql.append("'");
		List<Map<String, Object>> list = dao.queryBySql(sql.toString());
		return list;
    }


	@Override
	public List<TLock> list(JqGridPager jqGridPager) {
		 String sql = "select t.sid,t.agtcode,t.checkStatus,t.communityid,t.pid,t.install_lock_name as installlockname,TO_CHAR (t.install_time,'YYYY-MM-DD hh24:mi:ss') as installtime,(select uname from sysopt where sid = t.install_work) installwork,t.install_telete as installtelete,t.status,t.checkcode,c.areacode,c.citycode,c.communityname,a.agtname,TO_CHAR (o.otime,'yyyy-MM-dd HH24:mi:ss') as otime from t05_locks t "
		 		+ "left join t03_community c on t.communityid=c.sid  "
		 		+ "left join t02_agtent a on a.agtcode=t.agtcode "
		 		+ "left join (select o.pid,max(o.otime) as otime from topenlog o group by pid) o on t.pid=o.pid";
	     return dao.query(sql, jqGridPager);
	}

	@Override
	public int countSizeApp(String where) {
		int count = dao.count("select count(t.sid) from t05_locks t where " + where );
		return count;
	}
	@Override
	public List<TLock> listPageApp(String where, int beginNum, int endNum) {
		StringBuffer sql =new StringBuffer();
		sql.append("select b.* from "
					+ "(select rownum rb,a.* from "
						+ "(select rownum rn,t.sid,t.communityid,t.pid,t.install_lock_name as installlockname,TO_CHAR (t.install_time,'YYYY-MM-DD') as installtime,t.status,s.uname,s.tel from t05_locks t "
						+ "left join t03_community c on t.communityid=c.sid "
						+ "left join sysopt s on c.adminuser= s.sid "
						+ "where");
						sql.append(where);
						sql.append(" )a ");
						sql.append(" where rn<= ");
						sql.append(endNum);
						sql.append(")");
					sql.append(" b where rb>");
					sql.append(beginNum);
//		String sql = "select t.sid,t.communityid,t.pid,t.install_lock_name as installlockname,TO_CHAR (t.install_time,'YYYY-MM-DD hh24:mi:ss') as installtime,t.status, "
//				+ "from t05_locks t "+ where;
		return dao.queryBySql(sql.toString());
	}


	@Override
	public void delete(Long id) {
		TLock tLock = (TLock) dao.getById(TLock.class, id);
        dao.delete(tLock);
	}
	@Override
	public void update(TLock tLock) throws Exception {
        dao.update(tLock);
	}

	@Override
	public void delete(List<Long> ids) {
		 for (Long id : ids) {
	            delete(id);
	     }
	}
	@Override
	public TLock add(TLock tLock) throws Exception {
		dao.save(tLock);
        return tLock;
	}

	private LocksInstallLog add(LocksInstallLog locksInstallLog) throws Exception {
		dao.save(locksInstallLog);
        return locksInstallLog;
	}

	/**
     * 硬件新增保存
	 * @param tLock
	 * @param type
	 * @param user 		当前用户
     */
    @LogAnnotation(operateDescribe="硬件新增")
    public Map<String, Object> addMethod(TLock tLock,String type,Sysopt user){
         try {
        	StringBuffer where =new StringBuffer();
        	where.append(" pid='");
   			where.append(tLock.getPid());
   			where.append("'");
   			TLock entity = getHql(where.toString());
   			if(entity == null){
   				result.put("code", 0);
                result.put("msg", "查询不到此pid，请检查后重新输入");
                return result;
   			}
   			if(!"1".equals(entity.getCheckStatus())){
     			result.put("code", 0);
                result.put("msg", "该硬件未检测或检查不通过，无法安装");
                return result;
     		}
   			if(StringUtils.isBlank(entity.getCheckCode())){
   				result.put("code", 0);
                result.put("msg", "锁的激活码不存在，请联系锁厂解决");
                return result;
   			}
   			if(!entity.getCheckCode().equals(tLock.getCheckCode())){
     			result.put("code", 0);
                result.put("msg", "锁的校验码不匹配，请检查后请重新输入");
                return result;
     		}
   			if(!user.getAgtCode().equals(entity.getAgtCode())){
   				result.put("code", 0);
                result.put("msg", "智能锁状态不符合安装要求，请联系商家");
                return result;
   			}

   			if(!"2".equals(type)){//需要转移的硬件，不需要验证是否已经安装
   				if("1".equals(entity.getStatus())){
   	   				result.put("code", 0);
   	   				result.put("msg", "该智能锁已被注册使用，请重新核对信息");
   	   				return result;
   	   			}
   				if(!"2".equals(entity.getStatus())){
   	   				result.put("code", 0);
   	   				result.put("msg", "锁的状态不符合安装，请联系商家");
   	   				return result;
   	   			}
   			}

//   			Sysopt  user= (Sysopt)getSession().getAttribute("user");  //todo Updated by Saber on 2017/7/27 上午11:23

   			if(StringUtils.isNotBlank(tLock.getInstallLockName())){
   				entity.setInstallLockName(tLock.getInstallLockName());
   			}else{
   				entity.setInstallLockName(tLock.getPid());
   			}
   			//接口安装锁

	   		 StringBuilder sql = new StringBuilder();
			 sql.append("from TCommunity where type='2' and sid='");
			 sql.append(user.getCommunityId());
			 sql.append("'");
			 TCommunity tCommunity = (TCommunity) getObject(sql.toString());
			 if(tCommunity == null){
				 result.put("code", 0);
	             result.put("msg", "查不到安装硬件到客户信息，请用锁厂客户身份登录");
	             return result;
			 }
			 entity.setStatus("1");
			 entity.setCommunityId(Long.toString(tCommunity.getSid()));
			 entity.setInstallTime(new Timestamp(System.currentTimeMillis()));
			 result = installLock(tCommunity,entity);
			 if (!"1".equals(result.get("code").toString())) {
				 throw new MdKnownRunTimeException(result.get("msg").toString());
			 }
   			update(entity);
   			if("2".equals(type)){//转移之后，之前的钥匙和开门日志都做失效处理
         		dao.updateBySql("update t06_keys set status='2' where pid='"+tLock.getPid()+"'");
         		dao.updateBySql("update topenlog set status='1' where pid='"+tLock.getPid()+"'");
         	}

        	result.put("objectId", tLock.getSid());
        	result.put("code", "1");
            result.put("msg", "操作成功");
         } catch (MdKnownRunTimeException e) {
        	 log.error("硬件保存失败", e);
        	 result.put("code", 0);
             result.put("msg", e.getMessage());
         }catch (Exception e) {
             log.error("硬件保存失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
         }
         return result;
    }

	 /**
     * 硬件修改保存
     */
    @LogAnnotation(operateDescribe="硬件修改")
    public Map<String, Object> updateMethod(TLock tLock){
    	 String msg = ValidateUtil.validate(tLock);
    	 result.put("objectId", tLock.getSid());
         if (msg == null || msg.trim().length() == 0) {
             try {
            	 TLock entity = get(tLock.getSid());
             	 entity.setAgtCode(tLock.getAgtCode());
             	 entity.setCommunityId(tLock.getCommunityId());
             	 entity.setPid(tLock.getPid());
             	 entity.setInstallWork(tLock.getInstallWork());
             	 entity.setInstallTelete(tLock.getInstallTelete());
             	 entity.setInstallTime(tLock.getInstallTime());
            	 update(entity);
                 result.put("code", 1);
                 result.put("msg", "操作成功");
             } catch (Exception e) {
                 log.error("硬件更新失败", e);
                 result.put("code", 0);
                 result.put("msg", "操作失败");
             }
         } else {
             result.put("code", 0);
             result.put("msg", msg);
         }
         return result;
    }

	/**
     * 删除
     */
    @LogAnnotation(operateDescribe="硬件删除")
    public Map<String, Object> deleteMethod(String param_ids) {
    	 try {
    		 result.put("objectId", param_ids);
             List<Long> ids = new LinkedList<Long>();
             for (String s : param_ids.split(",")) {
                 ids.add(Long.parseLong(s));
             }
             delete(ids);
             result.put("code", 1);
             result.put("msg", "操作成功");
         } catch (Exception e) {
             log.error("硬件删除失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
         }
    	 return result;
    }

    /**
     * 硬件分配
	 * @param agtcode 		接收方id（T02_AGTENT主键）
	 * @param communityId	接收方社区id
	 * @param sids
	 * @param user			当前用户
	 * @param userRole		当前用户userRole
     */
	@Override
	@LogAnnotation(operateDescribe="硬件分配")
	public Map<String, Object> sendToTagentMethod(String agtcode, String communityId, String sids,Sysopt user,int userRole)  throws Exception {
    	 try {
        	String pids = getPids(sids);
        	result.put("objectId", pids);
        	if (StringUtils.isBlank(pids)) {
        		result.put("code", 0);
        		result.put("msg", "pid为空！");
        		return result;
			}
        	//发货
        	sendToTaget(agtcode,communityId, pids,user,userRole);
         } catch (Exception e) {
             log.error("硬件分配失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
             throw new MdKnownRunTimeException("硬件分配失败");
         }
        return result;
	}

	/**
	 * 发货
	 * @param agtcode		接收方代理商id(T02_AGTENT主键)
	 * @param communityId	接收方社区id
	 * @param pids			设备出厂编号
	 * @return
	 */
	private Map<String, Object> sendToTaget(String agtcode, String communityId, String pids,Sysopt user,int userRole) {
		 try {
			 if(StringUtils.isBlank(pids)){
				result.put("code", "0");
    			result.put("msg", "未找到能分配的智能门禁，请确定是否选择门禁或者所填写的门禁PID有效");
    			return result;
			 }
//		Sysopt  user= (Sysopt)getSession().getAttribute("user");		//todo Updated by Saber on 2017/7/27 上午11:24
//    	int userRole =  (Integer) getSession().getAttribute("userRole"); //todo Updated by Saber on 2017/7/27 上午11:24

			 //todo 不能发货给自己 Created by Saber on 2017/7/27 上午10:15
		/*	 if(agtcode.equals(user.getAgtCode())){//TODO 2017-8-8 22:27:59 wangk 判断有问题，小区会自己取自己
				 result.put("code","0");
				 result.put("msg","不能发货给自己,请重新选择");
				 return result;
			 }*/

    	TLock entity = null;
    	if (userRole == 1 || userRole == 2 || userRole == 7 ) { //todo Updated by Saber on 2017/7/25 下午5:37
			//接口去开发平台更改硬件的agetcode
    		 result = changeTlockAgt(pids,agtcode);
    		 if (!"1".equals(result.get("code").toString())) {
    			 return result;
    		 }
    	}

    	boolean ifInstall = false;
    	TAgent tAgent = null;
    	if (StringUtils.isNotBlank(agtcode)) {
    		tAgent = tAgentService.get(agtcode);
		}
   		if(tAgent != null && "1".equals(tAgent.getType()) || "2".equals(tAgent.getType())){ //todo Updated by Saber on 2017/7/26 上午9:31
   			ifInstall = true;
   		}
   		if(ifInstall){
   			StringBuilder where = new StringBuilder("from AppStore where 1=1 ");
    		where.append(" and agtCode ='");
    		where.append(tAgent.getAgtCode());
    		where.append("'");
    		AppStore appStores = (AppStore) appStoreService.get(where.toString());
    		if(appStores==null){
    			result.put("code", "-1");
    			result.put("msg", "该合作方还未指定APPID,请先增加应用");
    			return result;
    		}
   		}
   		String[] arr = pids.split(",");
    	for (String s : arr) {
    		StringBuffer where =new StringBuffer();
			where.append(" pid='");
   			where.append(s);
   			where.append("'");
        	 entity = getHql(where.toString());
        	 if (userRole == 1 || userRole == 2 || userRole == 7 ) { //平台发货 todo Updated by Saber on 2017/7/25 下午5:38
				 entity.setAgtCode(agtcode);


        		 if(ifInstall){//接口去自动安装锁
        			 StringBuilder sql = new StringBuilder();
        			 sql.append("from TCommunity where type='1' and agtCode='");
        			 sql.append(agtcode);
        			 sql.append("'");
        			 TCommunity tCommunity = (TCommunity) getObject(sql.toString());
        			 entity.setInstallLockName(entity.getPid());
        			 entity.setStatus("2"); //0:未安装,1:已安装,-1：未发货,2:锁厂测试安装
        			 entity.setCommunityId(Long.toString(tCommunity.getSid()));
        			 entity.setInstallTime(new Timestamp(System.currentTimeMillis()));
        			 entity.setcTime(new Timestamp(System.currentTimeMillis()));
        			 entity.setcUserName(Long.toString(user.getSid()));
        			 entity.setType("1");
        			 entity.setCheckStatus("0");
        			 result = installLock(tCommunity,entity);
        			 if (!"1".equals(result.get("code").toString())) {
        				 throw new MdKnownRunTimeException("硬件自动安装失败");
        			 }
        		 }
        	 }else if (userRole == 3 || userRole == 4) { //物业公司 锁厂发货
        		 entity.setCommunityId(communityId);
        		 entity.setStatus("0"); //0:未安装,1:已安装,-1：未发货,2:锁厂测试安装
				 entity.setDcUserName(Long.toString(user.getSid()));
        		 entity.setDcTime(new Timestamp(System.currentTimeMillis()));
        	 }
        	 update(entity);
         }
    	LocksDeliveryLog locksDeliveryLog = new LocksDeliveryLog();
    	if (userRole == 1 || userRole == 2) {
			if(pids.length()>1800){
    			String pidsBegin = pids.substring(0, 500);
    			String pidsEnd = pids.substring(pids.length()-500, pids.length());
    			locksDeliveryLog.setComm("分配硬件编号："+pidsBegin+"..."+pidsEnd+"，公司："+tAgent.getAgtName()+" 编号:"+tAgent.getAgtCode()+"，共"+pids.split(",").length+"个。");
    		}else{
    			locksDeliveryLog.setComm("分配硬件编号："+pids+"，公司："+tAgent.getAgtName()+" 编号:"+tAgent.getAgtCode()+"，共"+pids.split(",").length+"个。");
    		}
    		 locksDeliveryLog.setType(0);//平台发货
    		 locksDeliveryLog.setAgtCode(tAgent.getAgtCode());
   	 	}else if(userRole == 7 ){//主板厂商发货 todo Updated by Saber on 2017/7/25 下午5:44
			if(pids.length()>1800){
				String pidsBegin = pids.substring(0, 500);
				String pidsEnd = pids.substring(pids.length()-500, pids.length());
				locksDeliveryLog.setComm("分配硬件编号："+pidsBegin+"..."+pidsEnd+"，公司："+tAgent.getAgtName()+" 编号:"+tAgent.getAgtCode()+"，共"+pids.split(",").length+"个。");
			}else{
				locksDeliveryLog.setComm("分配硬件编号："+pids+"，公司："+tAgent.getAgtName()+" 编号:"+tAgent.getAgtCode()+"，共"+pids.split(",").length+"个。");
			}
			locksDeliveryLog.setType(0);//平台发货 //todo type 0:平台发货  1:一般合作商发货  2:主板厂商发货
			locksDeliveryLog.setAgtCode(tAgent.getAgtCode());
		}else if (userRole == 3 || userRole == 4) {
   	 		TCommunity tCommunity = (TCommunity) getObject(TCommunity.class,Long.parseLong(communityId));
	   	 	if(pids.length()>1800){
				String pidsBegin = pids.substring(0, 500);
				String pidsEnd = pids.substring(pids.length()-500, pids.length());
				locksDeliveryLog.setComm("分配硬件编号："+pidsBegin+"..."+pidsEnd+"，社区："+tCommunity.getCommunityName()+" 编号:"+tCommunity.getSid()+"，共"+pids.split(",").length+"个。");
			}else{
				locksDeliveryLog.setComm("分配硬件编号："+pids+"，社区："+tCommunity.getCommunityName()+" 编号:"+tCommunity.getSid()+"，共"+pids.split(",").length+"个。");
			}
   	 		locksDeliveryLog.setType(1);
   	 		locksDeliveryLog.setAgtCode(tCommunity.getAgtCode());
   	 	}
    	HttpServletRequest request /*= ServletActionContext.getRequest()*/;//todo Updated by Saber on 2017/8/17 下午12:12
			 if(ActionContext.getContext()!=null){  //判断是struts调用还是springmvc调用
				 request = ServletActionContext.getRequest();	//以struts方式取request
			 }else {
				 request = request=CommonUtil.getHttpRequest(); //以springmvc方式取request
			 }
		locksDeliveryLog.setcIp(WriteOperateLog.getIpAddr(request));
    	locksDeliveryLog.setcTime(new Timestamp(System.currentTimeMillis()));
    	locksDeliveryLog.setcUserName(Long.toString(user.getSid()));
    	locksDeliveryLog.setdType("0");
    	locksDeliveryLog.setLockNum(pids.split(",").length+"");
    	java.util.Arrays.sort(arr);
    	locksDeliveryLog.setPidFrom(arr[0]);
    	locksDeliveryLog.setPidTo(arr[arr.length-1]);
    	add(locksDeliveryLog);

			 //todo 记录锁的拥有者 Created by Saber on 2017/7/27 上午9:46
			 recordLockOwner(entity.getSid(),entity.getPid(),user.getAgtCode(),agtcode);

         result.put("code", 1);
         result.put("msg", "操作成功,共发货："+pids.split(",").length+"个");
		 } catch (Exception e) {
             log.error("硬件分配失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
             throw new MdKnownRunTimeException("硬件分配失败");
         }
        return result;
	}

	/**
	 *
	 * @param agtCode
	 * @param communityId
	 * @param pidBegin
	 * @param pidEnd
	 * @param user			当前用户
	 * @param userRole		当前用户userRole
	 * @return
	 */
	@Override
	public Map<String, Object> sendToBatchTagentMethod(String agtCode, String communityId, String pidBegin,
			String pidEnd,Sysopt user,int userRole) {

		 try {

			StringBuffer sql = new StringBuffer(
					"select XMLAGG(XMLELEMENT(E, pid || ',')).EXTRACT('//text()').getclobval() as pids from T05_LOCKS t where ");
			if(communityId!=null){//分配给社区
				sql.append("t.communityid is null  and t.agtcode='"+agtCode+"'  and t.pid>= '");
				sql.append(pidBegin);
				sql.append("' and t.pid <='");
				sql.append(pidEnd);
				sql.append("'");
			}else if(agtCode!=null){//分配给合作方
				sql.append("t.agtcode is null  and t.status ='-1' and t.pid>= '");
				sql.append(pidBegin);
				sql.append("' and t.pid <='");
				sql.append(pidEnd);
				sql.append("'");

			}else{
				sql.append("1=2");//其他情况则不取数据
			}

			List<Map<String, Object>> listPid = dao.queryBySql(sql.toString());

    		//List<Map<String, Object>> listPid = getPidToPid(pidBegin,pidEnd);
    		if (listPid.size()<1 || listPid.get(0).get("PIDS") == null) {
    			result.put("code", "-1");
    			result.put("msg", "找不到匹配的pid,无法分配");
    			return result;
    		}
    		String pids  =listPid.get(0).get("PIDS").toString();
    		pids = pids.substring(0,pids.length()-1);
    		System.out.println(pids);

    		result.put("objectId", pids);
        	//发货
        	sendToTaget(agtCode,communityId, pids,user,userRole);//todo Updated by Saber on 2017/7/27 上午11:35
		 } catch (Exception e) {
             log.error("硬件分配失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
             throw new MdKnownRunTimeException("硬件分配失败");
         }
        return result;
	}


	/**
	 * 自动安装锁
	 * @param tCommunity
	 * @param entity
	 * @return
	 */
	public Map<String, Object> installLock(TCommunity tCommunity, TLock entity) {
		try{
			result = installTlockAgt(entity,tCommunity.getAgtCode(),tCommunity.getPlatDepartId());
		}catch(Exception e) {
            log.error("自动安装锁失败", e);
            result.put("code", 0);
            result.put("msg", "自动安装锁失败");
		}
		return result;
	}

	/**
	 * 锁自动安装
	 * @param entity
	 * @param agtcode
	 * @param platDepartId
	 * @return
	 */
	private Map<String, Object> installTlockAgt(TLock entity, String agtcode, String platDepartId) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String,String> map = tAgentService.getPlatAppKey(agtcode);

			 MdOpenBaseJson json = MdOpenApi.installLock(entity,map.get("agt_num"),map.get("app_key"),platDepartId);
			if(json.isSuccess()){
				result.put("code", 1);
      	        result.put("msg", "操作成功");
			}else{
				log.error("安装硬件，同步到开放平台失败，json:"+json);
				result.put("code", 2);
      	        result.put("msg", "硬件安装，同步失败:"+json.getMsg().toString().replaceAll("[^0-9\\u4e00-\\u9fa5]", ""));
			}
    	} catch (Exception e) {
    		log.error("安装硬件，同步到开放平台失败", e);
    		result.put("code", 0);
  	        result.put("msg", "安装硬件，同步到开放平台失败");
    	}
		return result;
	}

	private String getPids(String sids) {
		List<String> listArr = new LinkedList<String>();
		if (StringUtils.isNotBlank(sids)) {
    		String[] arr = sids.split(",");
    		listArr = Arrays.asList(arr);
    	}
    	final List<Long> rids = new LinkedList<Long>();
    	for (String str : listArr) {
			rids.add(Long.parseLong(str));
		}
		if (rids == null || rids.size() == 0 ) {	//todo 增加size判断比较准确 Updated by Saber on 2017/8/16 下午12:51
//			 result.put("code", 0);
//             result.put("msg", "pid为空！");
             return null;
		}
		//查询pid
		 //获取角色中的菜单id集合
//        String sql = "from TLock where sid in (:ids)";		//todo Updated by Saber on 2017/8/16 下午12:44
//        List<TLock> list = dao.executeFind(sql,"ids",rids);	//todo Updated by Saber on 2017/8/16 下午12:44
		List<TLocksEntity> list = tLocksDao.getListBySids(rids); //todo 改用mybatis Created by Saber on 2017/8/16 下午12:45
		if (list == null || list.size() <1) {
//        	 result.put("code", 0);
//             result.put("msg", "pid为空！");
             return null;
		}
        StringBuffer pid =new StringBuffer();
        for (TLocksEntity tLock : list) {						//todo 改用mybatis Created by Saber on 2017/8/16 下午12:45
//        for (TLock tLock : list) {							//todo Updated by Saber on 2017/8/16 下午12:44
        	if (pid.length() !=0) {
    			pid.append(",");
    		}
    		pid.append(tLock.getPid());
		}
        return pid.toString();
	}

	private LocksDeliveryLog add(LocksDeliveryLog locksDeliveryLog) throws Exception {
		dao.save(locksDeliveryLog);
        return locksDeliveryLog;
	}

	/**
     * 硬件安装
	 * @param id
	 * @param type
	 * @param building
	 * @param unit
	 * @param name
	 * @param user 			当前用户
	 * @throws Exception
     */
	@Override
	@LogAnnotation(operateDescribe="硬件安装")
	public Map<String, Object> installTlocksMethod(String id, String type, String building, String unit, String name,Sysopt user) throws Exception {
   		 	result.put("objectId", id);
//   		 	Sysopt  user= (Sysopt)getSession().getAttribute("user"); //todo 仅注释本行 Updated by Saber on 2017/7/27 上午10:54
//   		 	CInstallUnit cInstallUnit = new CInstallUnit();
//   		 	if ("1".equals(type)) {
//	   		 	cInstallUnit.setCbName(name);
//				cInstallUnit.setIsPubUnit("1");
//				cInstallUnit.setcUserName(Long.toString(user.getSid()));
//				cInstallUnit.setcTime(new Timestamp(System.currentTimeMillis()));
//				cInstallUnit = cInstallUnitService.add(cInstallUnit);
//			}
   		 	TLock entity = get(Long.parseLong(id));
   		 	entity.setInstallLockName(name);
   		 	entity.setInstallWork(user.getSid().toString());
   		 	entity.setInstallTime(new Timestamp(System.currentTimeMillis()));
   		    entity.setIsPubUnit(type);
   		 	if ("0".equals(type)) {
				entity.setInstallunitId(unit);
			}
   		 	HttpServletRequest request = ServletActionContext.getRequest();
   		 	entity.setInstallGps(WriteOperateLog.getIpAddr(request));
   		 	entity.setStatus("1");
   		 	TCommunity tCommunity = (TCommunity) getObject(TCommunity.class,Long.parseLong(user.getCommunityId()));
   		 	entity.setIntallComm("安装硬件PID编号："+entity.getPid()+" 门禁名称："+name+" 到  "+tCommunity.getCommunityName()+"， 共一个。");
   		 	//调用接口
   		 	result = SyncTo(entity,user);
   		 	if (!"1".equals(result.get("code").toString())) {
   		 		throw new MdKnownRunTimeException((String)result.get("msg"));
			}
   		 	update(entity);
   		 LocksInstallLog locksInstallLog = new LocksInstallLog();
   		 locksInstallLog.setAgtCode(entity.getAgtCode());
   		 locksInstallLog.setComm(entity.getIntallComm());
   		 locksInstallLog.setCommunityId(entity.getCommunityId());
   		 locksInstallLog.setcTime(new Timestamp(System.currentTimeMillis()));
   		 locksInstallLog.setcUserName(user.getSid().toString());
  		 locksInstallLog.setInstallAddress(entity.getInstallAddress());
  		 locksInstallLog.setInstallGps(entity.getInstallGps());
  		 locksInstallLog.setInstallLockName(entity.getInstallLockName());
  		 locksInstallLog.setPid(entity.getPid());
  		 add(locksInstallLog);
   	 return result;
	}
	/**
	 * 用激活码的情况下会使用到，communityid、agtcode
	 * @param id
	 * @param type
	 * @param building
	 * @param unit
	 * @param name
	 * @param communityid
	 * @param agtcode
	 * @param user 			当前用户
	 * @return
	 */
	@Override
	@LogAnnotation(operateDescribe="硬件安装")
	public Map<String, Object> installTlocksMethod(String id, String type, String building, String unit, String name,
			String communityid, String agtcode,Sysopt user) throws Exception {
		result.put("objectId", id);
//		Sysopt user = (Sysopt) getSession().getAttribute("user");  //todo  Updated by Saber on 2017/7/27 上午10:59

		TLock entity = get(Long.parseLong(id));
		entity.setInstallLockName(name);
		entity.setInstallWork(user.getSid().toString());
		entity.setInstallTime(new Timestamp(System.currentTimeMillis()));
		entity.setIsPubUnit(type);
		if ("0".equals(type)) {
			entity.setInstallunitId(unit);
		}
		HttpServletRequest request = ServletActionContext.getRequest();
		entity.setInstallGps(WriteOperateLog.getIpAddr(request));
		entity.setStatus("1");
		entity.setAgtCode(agtcode);
		entity.setCommunityId(communityid);
		TCommunity tCommunity = (TCommunity) getObject(TCommunity.class, Long.parseLong(user.getCommunityId()));
		entity.setIntallComm(
				"安装硬件PID编号：" + entity.getPid() + " 门禁名称：" + name + " 到  " + tCommunity.getCommunityName() + "， 共一个。");
		// 调用接口
		result = SyncTo(entity,user);
		if (!"1".equals(result.get("code").toString())) {
			throw new MdKnownRunTimeException((String) result.get("msg"));
		}
		update(entity);
		LocksInstallLog locksInstallLog = new LocksInstallLog();
		locksInstallLog.setAgtCode(entity.getAgtCode());
		locksInstallLog.setComm(entity.getIntallComm());
		locksInstallLog.setCommunityId(entity.getCommunityId());
		locksInstallLog.setcTime(new Timestamp(System.currentTimeMillis()));
		locksInstallLog.setcUserName(user.getSid().toString());
		locksInstallLog.setInstallAddress(entity.getInstallAddress());
		locksInstallLog.setInstallGps(entity.getInstallGps());
		locksInstallLog.setInstallLockName(entity.getInstallLockName());
		locksInstallLog.setPid(entity.getPid());
		add(locksInstallLog);
		return result;
	}



	/**
	 * 硬件安装接口
	 * @param entity
	 * @return
	 */
	public Map<String, Object> SyncTo(TLock entity,Sysopt user) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String,String> map = tAgentService.getPlatAppKey(null);
//			Map<String,String> map = new HashMap<String, String>();
//			map.put("agt_num", Config.MD_OPEN_AGT_NUM);
//			map.put("app_key", Config.MD_OPEN_APP_KEY);
//			Sysopt  user= (Sysopt)getSession().getAttribute("user"); //todo Updated by Saber on 2017/7/27 上午11:04
			TCommunity tCommunity = (TCommunity) getObject(TCommunity.class,Long.parseLong(user.getCommunityId()));
			MdOpenBaseJson json = MdOpenApi.installLock(entity,map.get("agt_num"),map.get("app_key"),tCommunity.getPlatDepartId());
			if(json.isSuccess()){
				result.put("code", 1);
      	        result.put("msg", "操作成功");
			}else{
				log.error("安装硬件，同步到开放平台失败，json:"+json);
				result.put("code", 2);
      	        result.put("msg", "硬件安装成功，同步失败:"+json.getMsg().toString().replaceAll("[^0-9\\u4e00-\\u9fa5]", ""));
			}
    	} catch (Exception e) {
    		log.error("安装硬件，同步到开放平台失败", e);
    		result.put("code", 0);
  	        result.put("msg", "安装硬件，同步到开放平台失败");
    	}
		return result;
	}



	/**
	 * 已安装门禁点
	 */
	@Override
	public List<LocksInstallLog> installList(JqGridPager jqGridPager) {
		 String sql = "select t.sid,t.comm,to_char(t.cTime,'yyyy-MM-dd HH24:mi:ss') as installTime,install_Gps as ip,sysopt.uname as installWork from t05_locks_installlog t left join sysopt on t.cUserName =sysopt.sid left join t02_agtent a on t.agtcode=a.agtcode";
	     return dao.query(sql, jqGridPager);
	}

	/**
	 * 发货记录
	 */
	@Override
	public List<LocksDeliveryLog> listLocksDeliveryLog(JqGridPager jqGridPager) {
		 String sql = "select t.sid,t.cip,TO_CHAR (t.cTime,'yyyy-MM-dd HH24:mi:ss') as cTime1,t.cTime,t.comm,s.uname as cUserName from T05_LOCKS_DELIVERYLOG t left join sysopt s on t.cUserName =s.sid";
	     return dao.query(sql, jqGridPager);
	}

	/**
	 * 门禁列表
	 */
	@Override
	public List<Map<String, String>> tlockList(String type, String communityId) {
		StringBuffer sb = new StringBuffer("select t.sid,t.communityId,t.status,t.install_lock_name as installLockName from t05_locks t where ");
		sb.append("t.communityId ='");
		sb.append(communityId);
		sb.append("' and t.status ='1'");
		if ("private".equals(type)) {
			sb.append(" and t.ispubunit='0' ");
    	}else if("share".equals(type)){
    		sb.append(" and t.ispubunit='1' ");
    	}

		List<Map<String, String>> list= dao.queryBySql(sb.toString());
		return list;
	}

	/**
	 *
	 * @param jqGridPager
	 * @param pid1
	 * @param pid2
	 * @param type
	 * @param user			当前用户
	 * @param userRole		当前用户userRole
	 * @return
	 */
	@Override
	public List<Map<String, Object>> recoveryListList(JqGridPager jqGridPager,String pid1, String pid2, String type,Sysopt user,int userRole) {
		StringBuffer sb = new StringBuffer();
		sb.append("select t.sid,t.status,t.install_lock_name,TO_CHAR (t.install_time,'yyyy-MM-dd HH24:mi:ss') as install_time,(select uname from sysopt where sid = t.install_work) installwork,t.install_telete as installtelete,t.pid,a.agtname,c.communityname,c.citycode,TO_CHAR (o.otime,'yyyy-MM-dd HH24:mi:ss') as otime from t05_locks t "
		 		+ "left join t03_community c on t.communityid=c.sid "
		 		+ "left join t02_agtent a on t.agtcode=a.agtcode "
		 		+ "left join (select o.pid,max(o.otime) as otime from topenlog o group by pid) o on t.pid=o.pid  "
		 		+ "where t.type='");
//		+ "where t.status='1'");
		sb.append(type);
		sb.append("'");
		if (StringUtils.isNotBlank(pid1)) {
			sb.append(" and t.pid >= '");
			sb.append(pid1);
			sb.append("'");
//			sb.append(" and t.pid like '%");
//    		sb.append(pid1.substring(0, 5));
//    		sb.append("%'");
        }
    	if (StringUtils.isNotBlank(pid2)) {
    		sb.append(" and t.pid <= '");
    		sb.append(pid2);
    		sb.append("'");
//    		if (StringUtils.isBlank(pid1)) {
//    			sb.append(" and t.pid like '%");
//        		sb.append(pid2.substring(0, 5));
//        		sb.append("%'");
//			}
        }

//    	Sysopt  user= (Sysopt)getSession().getAttribute("user");			//todo Updated by Saber on 2017/7/27 上午11:41
//    	int userRole =  (Integer) getSession().getAttribute("userRole");    //todo Updated by Saber on 2017/7/27 上午11:42
		if (userRole == 1 || userRole == 2) {
    		sb.append(" and t.agtcode is not null ");
    	}else if (userRole == 3 || userRole == 4) {
			sb.append(" and t.agtCode ='");
			sb.append(user.getAgtCode());
			sb.append("' and t.communityId is not null");
		}else{
			return null;
		}
	     return dao.query(sb.toString(), jqGridPager);
	}

	/**
	 * 硬件回收
	 * Updated by Saber on 2017/7/27 上午10:48
	 * @param pids 		设备编号集合,使用,分割
	 * @param user 		当前用户
	 * @param userRole 	当前用户userRole
	 */
	@Override
	@LogAnnotation(operateDescribe="硬件回收")
	public Map<String, Object> recoveryMethod(String pids,Sysopt user,int userRole) {
		try {
   		 	result.put("objectId", pids);
   		 	if (StringUtils.isBlank(pids)) {
	   		 	result.put("code", 0);
	            result.put("msg", "硬件pid为空，操作失败");
	            return result;
			}
   		 	String[] pidArr = pids.split(",");
//   		 	Sysopt  user= (Sysopt)getSession().getAttribute("user"); //todo Updated by Saber on 2017/7/27 上午10:46
//   		 	int userRole =  (Integer) getSession().getAttribute("userRole");
	   		if (userRole == 3 || userRole == 4) {
	   			boolean bool = havaRole(pidArr,user);
	   			if (!bool) {
	   				result.put("code", 0);
		            result.put("msg", "没有对相应pid操作权限");
		            return result;
				}

	 		}else if (userRole == 5 || userRole == 6) {
	 			result.put("code", 0);
	            result.put("msg", "没有权限");
	            return result;
	 		}

   			for (int i = 0; i < pidArr.length; i++) {
   				StringBuffer where =new StringBuffer();
   				where.append(" pid='");
   				where.append(pidArr[i]);
   				where.append("'");
   				TLock tLock = getHql(where.toString());
   				TLock tLockClon = new TLock();
   				BeanUtils.copyProperties(tLock,tLockClon);
   				if (tLock == null) {
   					continue;
   				}
   				if(user.getrLevel()==3){//设置为锁厂预安装状态
   		   			StringBuilder sql = new StringBuilder();
   		   			 sql.append("from TCommunity where type='1' and agtCode='");
   		   			 sql.append(user.getAgtCode());
   		   			 sql.append("'");
   		   			 TCommunity tCommunity = (TCommunity) getObject(sql.toString());
   		   			 tLock.setInstallLockName(tLock.getPid());
   		   			 tLock.setStatus("2");
			   		 tLock.setCommunityId(Long.toString(tCommunity.getSid()));
			   		 tLock.setInstallTime(new Timestamp(System.currentTimeMillis()));
			   		 tLock.setcTime(new Timestamp(System.currentTimeMillis()));
			   		 tLock.setcUserName(Long.toString(user.getSid()));
			   		 tLock.setType("1");
   		   			 result = installLock(tCommunity,tLock);
   		   			 if (!"1".equals(result.get("code").toString())) {
   		   				 throw new MdKnownRunTimeException("硬件自动安装失败");
   		   			 }
   		   		}else{//设置为未发货状态
   		   			tLock.setStatus("-1");
   		   			tLock.setcComm("");
   		   			tLock.setCommunityId("");
   		   			tLock.setDcComm("");
   		   			tLock.setDcTime(null);
   		   			tLock.setDcUserName("");
   		   			tLock.setInstallAddress("");
   		   			tLock.setInstallGps("");
   		   			tLock.setInstallLockName("");
   		   			tLock.setInstallTelete("");
   		   			tLock.setInstallTime(null);
   		   			tLock.setInstallunitId("");
   		   			tLock.setInstallWork("");
   		   			tLock.setIntallComm("");
   		   			tLock.setType("0");
   		   			tLock.setIsPubUnit("");
   		   			if (userRole == 1 || userRole == 2) {
   		   				tLock.setAgtCode("");
   		   			}
   		   		}
   				update(tLock);
   				addLocksDeliveryLog(pidArr[i],tLockClon,user,userRole);
   				invalidKeys(tLock.getPid());
   				dao.updateBySql("update t06_keys set status='2' where pid='"+pidArr[i]+"'");//设置开门日期不可见
         		dao.updateBySql("update topenlog set status='1' where pid='"+pidArr[i]+"'");//设置开门日志
         		dao.updateBySql("delete from t06_keys_prolong  where pid='"+pidArr[i]+"'");

				//todo 删除设备历史拥有者表记录 Updated by Saber on 2017/7/27 下午1:14
				deleteLockOwnerRecord(tLock.getSid(),tLock.getPid(),user.getAgtCode());

	   		}

             result.put("code", 1);
             result.put("msg", "操作成功");
        } catch (Exception e) {
            log.error("硬件回收失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
            throw new MdKnownRunTimeException("硬件回收异常");
        }
   	 return result;
	}


	/**
	 * 回收硬件后钥匙失效
	 * @param pid
	 */
	private void invalidKeys(String pid) {
		String sql = "update T06_KEYS set status=1 where pid='"+pid+"'";
		dao.updateBySql(sql);
	}

	/**
	 * 日志
	 * @param pid
	 * @param tLockClon
	 */
	private void addLocksDeliveryLog(String pid, TLock tLockClon,Sysopt user,int userRole) {
		try {
//			Sysopt  user= (Sysopt)getSession().getAttribute("user");			//todo Updated by Saber on 2017/7/27 上午11:43
//			int userRole =  (Integer) getSession().getAttribute("userRole");    //todo Updated by Saber on 2017/7/27 上午11:43
			LocksDeliveryLog locksDeliveryLog = new LocksDeliveryLog();
	    	if (userRole == 1 || userRole == 2) {
	    		TAgent tAgent = tAgentService.get(tLockClon.getAgtCode());
	    		if(tAgent == null){
	    			locksDeliveryLog.setComm("回收硬件编号："+pid+"，公司： 未知，编号:未知，共1个。");
	    		}else{
	    			locksDeliveryLog.setComm("回收硬件编号："+pid+"，公司："+tAgent.getAgtName()+" 编号:"+tAgent.getAgtCode()+"，共1个。");
	    		}
	    		 locksDeliveryLog.setType(0);
	   	 	}else if (userRole == 3 || userRole == 4) {
	   	 		TCommunity tCommunity = (TCommunity) getObject(TCommunity.class,Long.parseLong(tLockClon.getCommunityId()));
	   	 		if (tCommunity==null) {
	   	 			locksDeliveryLog.setComm("回收硬件编号："+pid+"，社区：未知，编号:未知，共1个。");
				}else{
					locksDeliveryLog.setComm("回收硬件编号："+pid+"，社区："+tCommunity.getCommunityName()+" 编号:"+tCommunity.getSid()+"，共1个。");
				}
	   	 		locksDeliveryLog.setType(1);
	   	 	}
	    	HttpServletRequest request = ServletActionContext.getRequest();
			locksDeliveryLog.setcIp(WriteOperateLog.getIpAddr(request));
	    	locksDeliveryLog.setAgtCode(tLockClon.getAgtCode());
	    	locksDeliveryLog.setcTime(new Timestamp(System.currentTimeMillis()));
	    	locksDeliveryLog.setcUserName(Long.toString(user.getSid()));
	    	locksDeliveryLog.setdType("1");
	    	locksDeliveryLog.setLockNum("1");
	    	locksDeliveryLog.setPidFrom(pid);
	    	locksDeliveryLog.setPidTo(pid);
	    	add(locksDeliveryLog);
		} catch (Exception e) {
			log.error(this, e);
			throw new MdKnownRunTimeException("保存回收日志异常");
		}
	}

	/**
	 * 判断是否有操作权限
	 * @param pidArr
	 * @param user 	当前用户
	 */
	private boolean havaRole(String[] pidArr,Sysopt user) {
		List<String> listArr = new ArrayList<String>();
		List<TLock> tLocks = new ArrayList<TLock>();
//		Sysopt  user= (Sysopt)getSession().getAttribute("user");  //todo Updated by Saber on 2017/7/27 上午10:49
		listArr = Arrays.asList(pidArr);
    	String sql = "from TLock where agtCode="+user.getAgtCode()+" and pid  in (:ids)";
    	tLocks = dao.executeFindS(sql,"ids",listArr);
    	if (tLocks.size() != pidArr.length) {
    		return false;
		}else{
			return true;
		}
	}

	@Override
	public List<TLock> listTLocks(JqGridPager jqGridPager) {
		String sql = "select * from T05_LOCKS";
	     return dao.query(sql, jqGridPager);
	}

	@Override
	public List<TLock> getBySql(String where) {
		StringBuffer sb = new StringBuffer("from TLock where 1=1 ");
		sb.append(where);
		return dao.query(sb.toString());
	}

	@Override
	public Map<String, String> getInstallTlock(Long sid) {
		String sql = "select t.*,b.sid as building,i.sid as unit,t.ispubunit as type from T05_LOCKS t "
				+ "left join t032_cinstallunit i on t.installunitid =i.sid "
				+ "left join t031_cbuilding b on i.cbuildingid=b.sid  where t.sid="+sid;
		List<Map<String, String>> list = dao.queryBySql(sql);
		if (list.size()>0) {
			 return list.get(0);
		}
	    return null;
	}

	/**
	 *
	 * @param id
	 * @param type
	 * @param building
	 * @param unit
	 * @param name
	 * @param beforeunit
	 * @param user			当前用户
	 * @return
	 * @throws Exception
	 */
	@Override
	@LogAnnotation(operateDescribe="修改硬件安装点")
	public Map<String, Object> updateMethod(String id, String type, String building, String unit, String name, String beforeunit,Sysopt user) throws Exception {
		result.put("objectId", id);
//	 	Sysopt  user= (Sysopt)getSession().getAttribute("user");//todo Updated by Saber on 2017/7/27 上午11:07
	 	TLock entity = get(Long.parseLong(id));

	 	entity.setInstallLockName(name);
	 	entity.setInstallWork(user.getSid().toString());
	 	entity.setInstallTime(new Timestamp(System.currentTimeMillis()));
	 	entity.setIsPubUnit(type);
	 	if ("0".equals(type)) {
			entity.setInstallunitId(unit);
		}else{
			entity.setInstallunitId("");
		}
	 	HttpServletRequest request = ServletActionContext.getRequest();
	 	entity.setInstallGps(WriteOperateLog.getIpAddr(request));
	 	entity.setStatus("1");
	 	TCommunity tCommunity = (TCommunity) getObject(TCommunity.class,Long.parseLong(user.getCommunityId()));
	 	entity.setIntallComm("修改安装硬件安装点，PID编号："+entity.getPid()+" 门禁名称："+name+" 到  "+tCommunity.getCommunityName()+"， 共一个。");
	 	//调用接口
	 	result = SyncTo(entity,user);
	 	if (!"1".equals(result.get("code").toString())) {
	 		throw new MdKnownRunTimeException((String)result.get("msg"));
	 	}
	 	update(entity);
	 	 LocksInstallLog locksInstallLog = new LocksInstallLog();
   		 locksInstallLog.setAgtCode(entity.getAgtCode());
   		 locksInstallLog.setComm(entity.getIntallComm());
   		 locksInstallLog.setCommunityId(entity.getCommunityId());
   		 locksInstallLog.setcTime(new Timestamp(System.currentTimeMillis()));
   		 locksInstallLog.setcUserName(user.getSid().toString());
  		 locksInstallLog.setInstallAddress(entity.getInstallAddress());
  		 locksInstallLog.setInstallGps(entity.getInstallGps());
  		 locksInstallLog.setInstallLockName(entity.getInstallLockName());
  		 locksInstallLog.setPid(entity.getPid());
  		 add(locksInstallLog);
	 	return result;
	}

	@Override
	public Map<String, Object> checkMethod(String param_ids, String type) {
		try {
   		 	result.put("objectId", param_ids);
            List<Long> ids = new LinkedList<Long>();
            for (String s : param_ids.split(",")) {
            	TLock tlock = get(Long.parseLong(s));
            	tlock.setCheckStatus(type);

//            	update(tlock);
            }

            result.put("code", 1);
            result.put("msg", "操作成功");
        } catch (Exception e) {
            log.error("硬件修改状态失败", e);
            result.put("code", 0);
            result.put("msg", "硬件修改状态失败");
        }
   	 return result;
	}

	@Override
	//根据pid和激活码校验门禁硬件
	public Long validateLock(String pid, String checkCode){
		Long msg = null;
		StringBuilder sb = new StringBuilder();
		sb.append("select * from t05_locks t where t.pid= '");
		sb.append(pid);
		sb.append("' and t.checkcode='");
		sb.append(checkCode);
		sb.append("' and t.status != '1'");
		List<Map<String, String>> list = dao.queryBySql(sb.toString());
		if(list.size()==1){
			msg = Long.valueOf(list.get(0).get("sid"));
		}
		return msg;
	}

	/**
	 * 硬件分配接口
	 * @param agtcode
	 * @param pids
	 * @param entity
	 * @return
	 */
	@Override
	public Map<String, Object> changeTlockAgt(String pids, String agtcode) {
		// TODO Auto-generated method stub
		Map<String, Object> result = new HashMap<String, Object>();
		try {
//			Map<String,String> map = tAgentService.getPlatAppKey(null);
			Map<String,String> map = new HashMap<String, String>();
			map.put("agt_num", Config.MD_OPEN_AGT_NUM);
			map.put("app_key", Config.MD_OPEN_APP_KEY);
			TAgent tAgent = tAgentService.get(Long.parseLong(agtcode));
			MdOpenBaseJson json = MdOpenApi.changeTlockAgt(pids,tAgent.getPlatAgtcode(),map.get("agt_num"),map.get("app_key"));
			if(json.isSuccess()){
				result.put("code", 1);
				result.put("msg", "操作成功");
			}else{
				log.error("硬件分配,同步到开放平台失败，json:"+json);
				result.put("code", 2);
				result.put("msg", "同步到开放平台失败:"+json.getMsg().toString().replaceAll("[^0-9\\u4e00-\\u9fa5]", ""));
			}
		} catch (Exception e) {
			log.error("同步到开放平台失败", e);
			result.put("code", 0);
			result.put("msg", "同步到开放平台失败");
		}
		return result;
	}

	@Override
	public TLock getByPid(String pid) {
		 String hql = "from TLock where pid='"+pid+"'";
	     return (TLock) dao.loadObject(hql);
	}


	/**
	 * 记录锁的拥有者
	 * @author Saber
	 * @Date 2017/7/26 下午7:29
	 * @param tLocksId		设备表id（T05-LOCKS）
	 * @param pId			设备出厂编号
	 * @param fromAgtCode	现任拥有者id（T02_AGTENT） 也叫发货人,初始值一般为平台
	 * @param toAgtCode		下任拥有者id（T02_AGTENT） 也叫收货人
	 */
	private void recordLockOwner(Long tLocksId,String pId,String fromAgtCode,String toAgtCode){

		//保存前先查询当前属于第几层级,也就是该锁经过了几次发货
		Integer lastLevel = tLocksHisOwnersDao.getLastInsertLevels(tLocksId, pId);
		lastLevel= lastLevel ==null ? 0:lastLevel;

		TLocksHisOwnersEntity entity = new TLocksHisOwnersEntity();
		entity.setTlockId(tLocksId);
		entity.setPid(pId);
		entity.setFromAgentCode(fromAgtCode);
		entity.setToAgentCode(toAgtCode);
		entity.setLevels(lastLevel.intValue()+1);//入库时值+1

		tLocksHisOwnersDao.insertSelective(entity);
	}

	/**
	 * 门禁回收清除当前用户发出的发货设备拥有者记录
	 * @author Saber
	 * @Date 2017/7/27 下午1:22
	 * @param tLocksId		设备表id（T05_LOCKS表主键）
	 * @param pId			设备出厂编号
	 * @param agtCode		当前用户所属合作方id（T02_AGTENT表主键）
	 */
	private void deleteLockOwnerRecord(Long tLocksId,String pId,String agtCode){
		/**
		 * 0 : 平台
		 * A : 主板
		 * B : 锁厂
		 * C : 物业
		 * D : 社区
		 * 发货方			接受方       当前发货次数
		 * 0 	 - 		 A				1
		 * A	 -		 B				2
		 * B	 -		 C				3
		 * C	 -		 D				4
		 */

		/**
		 * 目前发货是单向且只能向下的 平台-->主板-->锁厂-->物业-->社区
		 * 1)平台回收,清除所有		where levels>=1
		 * 2)A回收,清除B、C、D	where levels>1
		 * 3)B回收,清除C、D		where levels>2
		 * 4)C回收,清除D			where levels>3
		 */

		// 判断agtCode是否为 0  如未0 则说明是平台执行回收 删除该条设备所有记录
		if("0".equals(agtCode)){
			tLocksHisOwnersDao.deleteByTLocksIdAndPid(tLocksId,pId);
			return;
		}

		Integer levels = tLocksHisOwnersDao.getFirstLevelsByToAgtCode(tLocksId, pId, agtCode);
		if( levels != null ){
			//删除记录
			tLocksHisOwnersDao.deleteByTLocksIdAndPidAndgtLevel(tLocksId,pId,levels);

		}

	}


//todo =======================================================================================================================================
	/**
	 * 分页查询
	 * @author Saber
	 * @Date 2017/7/27 下午7:03
	 * @param pageEntity	分页对象
	 * @param param 		查询参数
	 * @param user 			当前用户
	 * @param userRole 		当前用户userRole
	 * @return
	 */
	@Override
	public PageInfo<TlockListSendVO> queryForPage(PageEntity pageEntity, TLocksSendParam param, Sysopt user, int userRole){

		//主板厂商   在这里的考虑是主板厂商只能发给锁厂 所以将type值固定为1 而不是前台传来的 //todo Updated by Saber on 2017/7/26 下午4:27
//		if (userRole == 7 ){
//			param.setType("1"); //todo Created by Saber on 2017/7/27 下午5:00
//		}
//
//		if (userRole == 1 || userRole == 2 || userRole == 21) {
//
//			//区域主管
//			if (userRole == 21) {
//				param.setSysoptId(user.getSid());
//			}
//
//		}else if (userRole == 3 || userRole == 4 || userRole == 7 ) { //todo Updated by Saber on 2017/7/25 下午5:16
//			param.setAgtCode(user.getAgtCode());
//		}else if (userRole == 5 || userRole == 6) {
//			param.setCommunityId(user.getCommunityId());
//		}

		//判断是否是直辖市
		boolean isMunicipalities = false;
		if (org.apache.commons.lang3.StringUtils.isNotBlank(param.getAreaCode())) {
			isMunicipalities = CityUtil.isMunicipalities(param.getAreaCode());
		}

		//执行分页
		PageHelper.startPage(pageEntity.getPageNo(),pageEntity.getPageSize());
		//排序
		String orderField = pageEntity.getSort();//驼峰命名-->下划线（对应数据库字段）
		String orderDirection = pageEntity.getOrder();
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderField)) {
			PageHelper.orderBy(orderField);
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderDirection)) {
				PageHelper.orderBy(orderField + " " + orderDirection);
			}
		}

		List<TlockListSendVO> list= tLocksDao.queryForList(param,isMunicipalities,user,userRole);
		return new PageInfo<>(list);
	}

    /**
     * 智能门禁回收列表
     *
     * @param pageEntity 分页对象
     * @param pId1       pId开始
     * @param pId2       pId截止
     * @param type       类型：0：一般合作方硬件，1：锁厂硬件
     * @param user       当前用户
     * @param userRole   当前用户userRole
     * @return
     * @author Saber
     * @Date 2017/8/1 上午10:51
     */
    @Override
    public PageInfo<TlockRecoveryListVO> recoveryList(PageEntity pageEntity, String pId1, String pId2, String type, Sysopt user, int userRole) {
        //执行分页
        PageHelper.startPage(pageEntity.getPageNo(),pageEntity.getPageSize());
        //排序
        String orderField = pageEntity.getSort();//驼峰命名-->下划线（对应数据库字段）
        String orderDirection = pageEntity.getOrder();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderField)) {
            PageHelper.orderBy(orderField);
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderDirection)) {
                PageHelper.orderBy(orderField + " " + orderDirection);
            }
        }
        String agtCode = null;
        //以前的条件判断
        if (userRole == 1 || userRole == 2) {
//            sb.append(" and t.agtcode is not null ");
        }else if (userRole == 3 || userRole == 4) {
//            sb.append(" and t.agtCode ='");
//            sb.append(user.getAgtCode());
//            sb.append("' and t.communityId is not null");
            agtCode=user.getAgtCode();
        }else{
            return null;
        }
        List<TlockRecoveryListVO> list= tLocksDao.recoveryList(pId1,pId2,type,userRole,agtCode);
        return new PageInfo<>(list);
    }

    /**
     * 智能门禁发胡列表
     *
     * @param pageEntity 分页对象
     * @param pId1       pId开始
     * @param pId2       pId结束
     * @param user       当前用户
     * @param userRole   当前用户userRole
     * @return
     * @author Saber
     * @Date 2017/8/1 下午12:49
     */
    @Override
    public PageInfo<TLocksEntity> notSendList(PageEntity pageEntity, String pId1, String pId2, Sysopt user, int userRole) {
            //执行分页
            PageHelper.startPage(pageEntity.getPageNo(),pageEntity.getPageSize());
            //排序
            String orderField = pageEntity.getSort();//驼峰命名-->下划线（对应数据库字段）
            String orderDirection = pageEntity.getOrder();
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderField)) {
                PageHelper.orderBy(orderField);
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderDirection)) {
                    PageHelper.orderBy(orderField + " " + orderDirection);
                }
            }
            String agtCode = null;
            //以前的条件判断
            if (userRole == 1 || userRole == 2) {
//                where.append(" and agtcode is null ");
            }else	if (userRole == 3 || userRole == 4 || userRole == 7 ) { //todo Updated by Saber on 2017/7/25 下午5:18
//                where.append(" and agtCode ='");
//                where.append(user.getAgtCode());
//                where.append("'");
                agtCode = user.getAgtCode();
            }else if (userRole == 5 || userRole == 6) {

            }else{
                return null;
            }
            List<TLocksEntity> list= tLocksDao.notSendList(pId1,pId2,userRole,agtCode);
            return new PageInfo<>(list);
    }


    /**
     * 智能门禁回收
     *
     * @param pIds     pId集合
     * @param user     当前用户
     * @param userRole 当前用户userRole
     * @return
     * @author Saber
     * @Date 2017/8/1 下午2:29
	 * @see TLocksServiceImpl#recoveryMethod(String, Sysopt, int)
     */
    @Override
    @Transactional
    public JSONObject recovery(String pIds, Sysopt user, int userRole) {

        JSONObject json = new JSONObject();
        try {
            json.put("data", pIds);
            if (StringUtils.isBlank(pIds)) {
                json.put("code", 0);
                json.put("msg", "硬件pid为空，操作失败");
                return json;
            }

            String[] pidArr = pIds.split(",");
            if (userRole == 3 || userRole == 4) {
                boolean bool = havaRole(pidArr,user);
                if (!bool) {
                    json.put("code", 0);
                    json.put("msg", "没有对相应pid操作权限");
                    return json;
                }

            }else if (userRole == 5 || userRole == 6) {
                json.put("code", 0);
                json.put("msg", "没有权限");
                return json;
            }

            for (int i = 0; i < pidArr.length; i++) {
                TLocksEntity tLock = tLocksDao.getByPid(pidArr[i]);
                TLocksEntity tLockClon = new TLocksEntity();
                BeanUtils.copyProperties(tLock,tLockClon);
                if (tLock == null) {
                    continue;
                }
                if(user.getrLevel()==3){//设置为锁厂预安装状态
                    String type = "1";
                    TCommunityEntity tCommunityEntity = tCommunityDao.getByTypeAndAgtCode(type,user.getAgtCode());
                    tLock.setInstallLockName(tLock.getPid());
                    tLock.setStatus("2");
                    tLock.setCommunityid(Long.toString(tCommunityEntity.getSid()));
                    tLock.setInstallTime(new Timestamp(System.currentTimeMillis()));
                    tLock.setCtime(new Timestamp(System.currentTimeMillis()));
                    tLock.setCusername(Long.toString(user.getSid()));
                    tLock.setType("1");
                    //自动安装锁
                    JSONObject installResult = installLockMy(tCommunityEntity, tLock);
                    if (!"1".equals(installResult.get("code").toString())) {
                        throw new MdKnownRunTimeException("硬件自动安装失败");
                    }
                }else{//设置为未发货状态
                    tLock.setStatus("-1");
                    tLock.setCcomm("");
                    tLock.setCommunityid("");
                    tLock.setDccomm("");
                    tLock.setDctime(null);
                    tLock.setDcusername("");
                    tLock.setInstallAddress("");
                    tLock.setInstallGps("");
                    tLock.setInstallLockName("");
                    tLock.setInstallTelete("");
                    tLock.setInstallTime(null);
                    tLock.setInstallunitid("");
                    tLock.setInstallWork("");
                    tLock.setIntallComm("");
                    tLock.setType("0");
                    tLock.setIspubunit("");
                    if (userRole == 1 || userRole == 2) {
                        tLock.setAgtcode("");
                    }
                }
                update(tLock);
                addLocksDeliveryLog(pidArr[i],tLockClon,user,userRole);
                invalidKeys(tLock.getPid());

                //设置开门日期不可见
                tkeysDao.updateStatusByPid("2",pidArr[i]);
                //设置开门日志
                tOpenlogDao.updateStatusByPid("1",pidArr[i]);
                tKeysProlongDao.deleteByPid(pidArr[i]);

                //todo 删除设备历史拥有者表记录 Updated by Saber on 2017/7/27 下午1:14
                deleteLockOwnerRecord(tLock.getSid(),tLock.getPid(),user.getAgtCode());

            }

            json.put("code", 1);
            json.put("msg", "操作成功");
            return json;
        } catch (Exception e) {
            log.error("硬件回收失败", e);
            json.put("code", 0);
            json.put("msg", "操作失败");
            throw new MdKnownRunTimeException("硬件回收异常");
        }

    }


    /**
     * 自动安装锁
     * @author Saber
     * @Date 2017/8/1 下午3:23
     * @param tCommunityEntity
     * @param tlockEntity
     * @return
     */
    public JSONObject installLockMy(TCommunityEntity tCommunityEntity, TLocksEntity tlockEntity) {
        JSONObject json = new JSONObject();
        try{

            //todo 为了调用原来的接口 在这里进行2个对象的转化, Created by Saber on 2017/8/1 下午3:01
            //todo 但这里会造成一个问题,如果实体类属性更改,如新增,则需要处理这里的代码
            TLock entity = new TLock();
            entity.setSid(tlockEntity.getSid());
            entity.setAgtCode(tlockEntity.getAgtcode());
            entity.setCommunityId(tlockEntity.getCommunityid());
            entity.setPid(tlockEntity.getPid());
            entity.setInstallLockName(tlockEntity.getInstallLockName());
            entity.setInstallAddress(tlockEntity.getInstallAddress());
            entity.setInstallGps(tlockEntity.getInstallGps());
            entity.setInstallTelete(tlockEntity.getInstallTelete());
            entity.setInstallTime(tlockEntity.getInstallTime());
            entity.setIntallComm(tlockEntity.getIntallComm());
            entity.setcUserName(tlockEntity.getCusername());
            entity.setcTime(tlockEntity.getCtime());
            entity.setcComm(tlockEntity.getCcomm());
            entity.setDcUserName(tlockEntity.getDcusername());
            entity.setDcTime(tlockEntity.getDctime());
            entity.setDcComm(tlockEntity.getDccomm());
            entity.setInstallunitId(tlockEntity.getInstallunitid());
            entity.setStatus(tlockEntity.getStatus());
            entity.setType(tlockEntity.getType());
            entity.setCheckCode(tlockEntity.getCheckcode());
            entity.setCheckStatus(tlockEntity.getCheckstatus());
            entity.setIsPubUnit(tlockEntity.getIspubunit());
            entity.setMac20(tlockEntity.getMac20());
            entity.setSsid1(tlockEntity.getSsid1());

            result = installTlockAgt(entity,tCommunityEntity.getAgtcode(),tCommunityEntity.getPlatDepartid());
            json.putAll(result);
        }catch(Exception e) {
            log.error("自动安装锁失败", e);
            json.put("code", 0);
            json.put("msg", "自动安装锁失败");
        }
        return json;
    }

    /**
     * 日志
     * @param pid           pId
     * @param tLockClon     tLocksEntity
     * @param user          当前用户
     * @param userRole      当前用户userRole
     */
    private void addLocksDeliveryLog(String pid, TLocksEntity tLockClon,Sysopt user,int userRole) {
        try {
            LocksDeliveryLog locksDeliveryLog = new LocksDeliveryLog();
            if (userRole == 1 || userRole == 2) {
                TAgent tAgent = tAgentService.get(tLockClon.getAgtcode());
                if(tAgent == null){
                    locksDeliveryLog.setComm("回收硬件编号："+pid+"，公司： 未知，编号:未知，共1个。");
                }else{
                    locksDeliveryLog.setComm("回收硬件编号："+pid+"，公司："+tAgent.getAgtName()+" 编号:"+tAgent.getAgtCode()+"，共1个。");
                }
                locksDeliveryLog.setType(0);
            }else if (userRole == 3 || userRole == 4) {
                TCommunity tCommunity = (TCommunity) getObject(TCommunity.class,Long.parseLong(tLockClon.getCommunityid()));
                if (tCommunity==null) {
                    locksDeliveryLog.setComm("回收硬件编号："+pid+"，社区：未知，编号:未知，共1个。");
                }else{
                    locksDeliveryLog.setComm("回收硬件编号："+pid+"，社区："+tCommunity.getCommunityName()+" 编号:"+tCommunity.getSid()+"，共1个。");
                }
                locksDeliveryLog.setType(1);
            }

            //todo 需要考虑 userRole=7 也就是主板厂商是否回收
            /**
             *   do something ...
             */

            HttpServletRequest request = CommonUtil.getHttpRequest();//此处使用的是springmvc提供的 request Created by Saber on 2017/8/1 下午3:38
            locksDeliveryLog.setcIp(WriteOperateLog.getIpAddr(request));
            locksDeliveryLog.setAgtCode(tLockClon.getAgtcode());
            locksDeliveryLog.setcTime(new Timestamp(System.currentTimeMillis()));
            locksDeliveryLog.setcUserName(Long.toString(user.getSid()));
            locksDeliveryLog.setdType("1");
            locksDeliveryLog.setLockNum("1");
            locksDeliveryLog.setPidFrom(pid);
            locksDeliveryLog.setPidTo(pid);
            add(locksDeliveryLog);
        } catch (Exception e) {
            log.error(this, e);
            throw new MdKnownRunTimeException("保存回收日志异常");
        }
    }

    /**
     * 智能门禁安装列表（未安装的列表）
     *
	 * @param pageEntity 分页对象
     * @param user       当前用户
     * @param userRole   当前用户userRole
     * @return
     * @author Saber
     * @Date 2017/8/1 下午4:39
     */
    @Override
    public PageInfo<TLocksEntity> installTlocksList(PageEntity pageEntity, Sysopt user, int userRole) {
        //执行分页
        PageHelper.startPage(pageEntity.getPageNo(), pageEntity.getPageSize());
        //排序
        String orderField = pageEntity.getSort();
        String orderDirection = pageEntity.getOrder();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderField)) {
            PageHelper.orderBy(orderField);
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderDirection)) {
                PageHelper.orderBy(orderField + " " + orderDirection);
            }
        }

        List<TLocksEntity> list = tLocksDao.installTlocksList(user.getCommunityId());
        return new PageInfo<>(list);
    }

	/**
	 * 门禁安装
	 * @author Saber
	 * @Date 2017/8/1 下午6:12
	 * @param request
	 * @param sId               sId
	 * @param isPubunit         0:私有门禁,1:公共门禁
	 * @param cBuildingId		楼栋id
	 * @param unitId     		单元id 对应于T032_CInstallUnit.SID 安装位置点编号在整个掌联系统中唯一编码
	 * @param lockName   		门禁名称
	 * @param user              当前用户
	 * @param userRole          当前用户userRole
	 * @see #installTlocksMethod(String, String, String, String, String, Sysopt)
	 * @return
	 */
    @Transactional
    @Override
    public JSONObject installTlocks(HttpServletRequest request, Long sId, String isPubunit, String cBuildingId, String unitId, String lockName, Sysopt user, int userRole) {
        JSONObject json = new JSONObject();

		//判断 sId是否为空 //todo Created by Saber on 2017/8/10 下午5:13
		if(sId == null){
			json.put("code",0);
			json.put("msg","请选择设备");
			json.put("data",null);
			return json;
		}

        json.put("data", sId);
        TLocksEntity entity = tLocksDao.selectByPrimaryKey(sId);
		//判断传来的sId是否有效 //todo Created by Saber on 2017/8/10 下午5:14
		if(entity == null){
			json.put("code",0);
			json.put("msg","当前设备不存在"+sId);
			json.put("data",null);
			return json;
		}
        entity.setInstallLockName(lockName);
        entity.setInstallWork(user.getSid().toString());
        entity.setInstallTime(new Timestamp(System.currentTimeMillis()));
        entity.setIspubunit(isPubunit);
        if ("0".equals(isPubunit)) {
            entity.setInstallunitid(unitId);
        }
        entity.setInstallGps(WriteOperateLog.getIpAddr(request));
        entity.setStatus("1");
        TCommunityEntity tCommunityEntity = tCommunityDao.selectByPrimaryKey(Long.valueOf(user.getCommunityId()));
		//判断小区是否存在 //todo Created by Saber on 2017/8/10 下午5:10
		if(tCommunityEntity==null){
			json.put("code",0);
			json.put("msg","当前用户所在的小区不存在"+user.getCommunityId());
			json.put("data",null);
			return json;
		}
        entity.setIntallComm("安装硬件PID编号："+entity.getPid()+" 门禁名称："+lockName+" 到  "+tCommunityEntity.getCommunityname()+"， 共一个。");
        //调用接口
        json = SyncTo(entity,user);
        if (!"1".equals(json.get("code").toString())) {
            throw new MdKnownRunTimeException((String)json.get("msg"));
        }
        //更新
        tLocksDao.updateByPrimaryKeySelective(entity);

        TLocksInstalllogEntity locksInstallLog = new TLocksInstalllogEntity();
        locksInstallLog.setAgtcode(entity.getAgtcode());
        locksInstallLog.setComm(entity.getIntallComm());
        locksInstallLog.setCommunityid(entity.getCommunityid());
        locksInstallLog.setCtime(new Timestamp(System.currentTimeMillis()));
        locksInstallLog.setCusername(user.getSid().toString());
        locksInstallLog.setInstallAddress(entity.getInstallAddress());
        locksInstallLog.setInstallGps(entity.getInstallGps());
        locksInstallLog.setInstallLockName(entity.getInstallLockName());
        locksInstallLog.setPid(entity.getPid());
        //新增
        tLocksInstalllogDao.insertSelective(locksInstallLog);
        return json;
    }

	/**
	 * 用激活码的情况下会使用到，communityid、agtcode
	 * @author Saber
	 * @Date 2017/8/1 下午6:46
	 * @param request
	 * @param sId               sId
	 * @param isPubunit         0:私有门禁安装点,1:公共门禁安装点
	 * @param cBuildingId		楼栋id
	 * @param unitId     		单元id 对应于T032_CInstallUnit.SID 安装位置点编号在整个掌联系统中唯一编码
	 * @param lockName   		安装钥匙名称
	 * @param communityid       社区id
	 * @param agtcode           合作方id
	 * @param user 			    当前用户
	 * @see #installTlocksMethod(String, String, String, String, String, String, String, Sysopt)
	 * @return
	 * @throws Exception
	 */
    @Transactional
    @Override
    public JSONObject installTlocks(HttpServletRequest request, Long sId, String isPubunit, String cBuildingId, String unitId, String lockName, String communityid, String agtcode, Sysopt user) {
        JSONObject json = new JSONObject();

        json.put("data", sId);

		//判断 sId是否为空 //todo Created by Saber on 2017/8/10 下午5:13
		if(sId == null){
			json.put("code",0);
			json.put("msg","请选择设备");
			json.put("data",null);
			return json;
		}

		json.put("data", sId);
		TLocksEntity entity = tLocksDao.selectByPrimaryKey(sId);
		//判断传来的sId是否有效 //todo Created by Saber on 2017/8/10 下午5:14
		if(entity == null){
			json.put("code",0);
			json.put("msg","当前设备不存在"+sId);
			json.put("data",null);
			return json;
		}

        entity.setInstallLockName(lockName);
        entity.setInstallWork(user.getSid().toString());
        entity.setInstallTime(new Timestamp(System.currentTimeMillis()));
        entity.setIspubunit(isPubunit);

        if ("0".equals(isPubunit)) { //0:私有门禁安装点,1:公共门禁安装点
            entity.setInstallunitid(unitId);
        }
        entity.setInstallGps(WriteOperateLog.getIpAddr(request));
        entity.setStatus("1");
        entity.setAgtcode(agtcode);
        entity.setCommunityid(communityid);
		TCommunityEntity tCommunityEntity = tCommunityDao.selectByPrimaryKey(Long.valueOf(user.getCommunityId()));
		//判断小区是否存在 //todo Created by Saber on 2017/8/10 下午5:10
		if(tCommunityEntity==null){
			json.put("code",0);
			json.put("msg","当前用户所在的小区不存在"+user.getCommunityId());
			json.put("data",null);
			return json;
		}
        entity.setIntallComm(
                "安装硬件PID编号：" + entity.getPid() + " 门禁名称：" + lockName + " 到  " + tCommunityEntity.getCommunityname() + "， 共一个。");
        // 调用接口
        json = SyncTo(entity,user);
        if (!"1".equals(json.get("code").toString())) {
            throw new MdKnownRunTimeException((String) json.get("msg"));
        }
        //更新
        tLocksDao.updateByPrimaryKeySelective(entity);

        TLocksInstalllogEntity locksInstallLog = new TLocksInstalllogEntity();
        locksInstallLog.setAgtcode(entity.getAgtcode());
        locksInstallLog.setComm(entity.getIntallComm());
        locksInstallLog.setCommunityid(entity.getCommunityid());
        locksInstallLog.setCtime(new Timestamp(System.currentTimeMillis()));
        locksInstallLog.setCusername(user.getSid().toString());
        locksInstallLog.setInstallAddress(entity.getInstallAddress());
        locksInstallLog.setInstallGps(entity.getInstallGps());
        locksInstallLog.setInstallLockName(entity.getInstallLockName());
        locksInstallLog.setPid(entity.getPid());
        //新增
        tLocksInstalllogDao.insertSelective(locksInstallLog);
        return json;
    }

    /**
     * 硬件安装接口
	 * @author Saber
	 * @Date 2017/8/1 下午6:46
     * @param entity
     * @return
     */
	@Transactional
    public JSONObject SyncTo(TLocksEntity entity,Sysopt user) {
        JSONObject json = new JSONObject();
        try {
            Map<String,String> map = tAgentService.getPlatAppKey(null);
            TCommunityEntity tCommunityEntity = tCommunityDao.selectByPrimaryKey(Long.valueOf(user.getCommunityId()));
            MdOpenBaseJson mdOpenBaseJson = MdOpenApi.installLock(entity, map.get("agt_num"), map.get("app_key"), tCommunityEntity.getPlatDepartid());
            if(mdOpenBaseJson.isSuccess()){
                json.put("code", 1);
                json.put("msg", "操作成功");
            }else{
                log.error("安装硬件，同步到开放平台失败，json:"+json);
                json.put("code", 2);
                json.put("msg", "硬件安装成功，同步失败:"+mdOpenBaseJson.getMsg().toString().replaceAll("[^0-9\\u4e00-\\u9fa5]", ""));
            }
        } catch (Exception e) {
            log.error("安装硬件，同步到开放平台失败", e);
            json.put("code", 0);
            json.put("msg", "安装硬件，同步到开放平台失败");
        }
        return json;
    }

	/**
	 * 智能门禁已安装记录列表接口
	 * @author Saber
	 * @Date 2017/8/10 下午2:59
	 *
	 * @param pageEntity       分页对象
	 * @param user             当前用户
	 * @param userRole         当前用户userRole
	 * @param operationContent 操作内容
	 * @param operator         操作人
	 * @param sendTime         操作时间
	 * @return
	 */
	@Override
	public PageInfo<TLocksInstalllogListVO> installLogList(PageEntity pageEntity, Sysopt user, int userRole, String operationContent, String operator, String sendTime) {
		//执行分页
		PageHelper.startPage(pageEntity.getPageNo(), pageEntity.getPageSize());
		//排序
		String orderField = pageEntity.getSort();
		String orderDirection = pageEntity.getOrder();
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderField)) {
			PageHelper.orderBy(orderField);
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(orderDirection)) {
				PageHelper.orderBy(orderField + " " + orderDirection);
			}
		}
		List<TLocksInstalllogListVO> list = tLocksInstalllogDao.installLogList(operationContent,operator,sendTime,userRole,user);
		return new PageInfo<>(list);
	}

	/**
	 * 门禁列表
	 * @author Saber
	 * @Date 2017/8/10 下午2:59
	 * @param type        钥匙类型 private :私有钥匙  share:共有钥匙
	 * @param communityId 小区id
	 * @param user        当前用户
	 * @param userRole    当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/10 下午2:38
	 * @see TLocksServiceImpl#tlockList(String, String)
	 */
	@Override
	public List<TlockListVO> tlockList(String type, String communityId, Sysopt user, int userRole) {

		return tLocksDao.tlockList(type,communityId,user,userRole);
	}

	/**
	 * 获取安装点详情
	 *
	 * @param sId sId
	 * @return
	 * @author Saber
	 * @Date 2017/8/11 上午10:06
	 * @see #getInstallTlock(Long)
	 */
	@Override
	public InstallTlockDetailVO getInstallTlockDetail(Long sId) {
		if (sId == null) return null;
		return tLocksDao.getInstallTlockDetail(sId);
	}

	/**
	 * 安装点修改
	 *
	 * @param request
	 * @param param    参数
	 * @param user     当前用户
	 * @param userRole 当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/11 下午12:21
	 * @see TLocksServiceImpl#updateMethod(String, String, String, String, String, String, Sysopt)
	 */
	@Override
	@Transactional
	public JSONObject update(HttpServletRequest request,UpdateTlockParam param, Sysopt user, int userRole) {

		JSONObject json = new JSONObject();

		//验证参数
		String msg = ValidateUtil.validate(param);
		if (org.apache.commons.lang3.StringUtils.isNotBlank(msg)) {
			json.put("code", 0);
			json.put("msg", msg);
			return json;
		}

		json.put("data", param.getsId());
		TLocksEntity entity = tLocksDao.selectByPrimaryKey(param.getsId());

		entity.setInstallLockName(param.getInstallLockName());
		entity.setInstallWork(user.getSid().toString());
		entity.setInstallTime(new Timestamp(System.currentTimeMillis()));
		entity.setIspubunit(param.getIsPubunit());
		if ("0".equals(param.getIsPubunit())) {
			entity.setInstallunitid(param.getCinstallUnitId());
		}else{
			entity.setInstallunitid("");
		}
		entity.setInstallGps(WriteOperateLog.getIpAddr(request));
		entity.setStatus("1");
		TCommunityEntity tCommunity = tCommunityDao.selectByPrimaryKey(Long.parseLong(user.getCommunityId()));
		entity.setIntallComm("修改安装硬件安装点，PID编号："+entity.getPid()+" 门禁名称："+param.getInstallLockName()+" 到  "+tCommunity.getCommunityname()+"， 共一个。");
		//调用接口
		json = SyncTo(entity,user);
//		json.put("code",1);			//运行测试类时注释掉 SyncTo(）方法使用
//		json.put("msg","操作成功");
		if (!"1".equals(json.get("code").toString())) {
			throw new MdKnownRunTimeException((String)json.get("msg"));
		}
		update(entity);
		TLocksInstalllogEntity locksInstallLog = new TLocksInstalllogEntity();
		locksInstallLog.setAgtcode(entity.getAgtcode());
		locksInstallLog.setComm(entity.getIntallComm());
		locksInstallLog.setCommunityid(entity.getCommunityid());
		locksInstallLog.setCtime(new Timestamp(System.currentTimeMillis()));
		locksInstallLog.setCusername(user.getSid().toString());
		locksInstallLog.setInstallAddress(entity.getInstallAddress());
		locksInstallLog.setInstallGps(entity.getInstallGps());
		locksInstallLog.setInstallLockName(entity.getInstallLockName());
		locksInstallLog.setPid(entity.getPid());
		tLocksInstalllogDao.insertSelective(locksInstallLog);
		return json;
	}


	/**
	 * 智能门禁更换
	 *
	 * @param sId       sId
	 * @param newPid    新门禁的sId
	 * @param checkCode 激活码
	 * @param user      当前用户
	 * @param userRole  当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/11 下午2:22
	 * @see com.eportal.action.background.TLocksAction#saveChange()
	 */
	@Override
	@Transactional
	public JSONObject saveChange(Long sId, String newPid, String checkCode, Sysopt user, int userRole) {
		JSONObject json = new JSONObject();

		try {

			//校验新设备
			TLocksEntity lock = tLocksDao.getByPid(newPid);
			if(lock!=null){
				if("1".equals(lock.getStatus())){
					json.put("code", 0);
					json.put("msg", "设备已被安装，请重新确认信息");
					json.put("data",null);
					return json;
				}
				if(!checkCode.equals(lock.getCheckcode())){
					json.put("code", 0);
					json.put("msg", "激活码不正确");
					return json;
				}
			}else{
				json.put("code", 0);
				json.put("msg", "没有匹配的硬件");
				return json;
			}

			Map map = this.changeTlockAgt(newPid, user.getAgtCode());// 执行发货操作
			if((Integer)map.get("code")==1){
				//这里为了解决循环依赖的问题 使用SpringContextHolder获取TKeysService
				TKeysService tKeysService = SpringContextHolder.getBean(TKeysService.class);
				//硬件更换，在硬件损坏等情况下，社区可以更换设备
				tKeysService.change(String.valueOf(sId), lock.getSid().toString(), user.getCommunityId(),user.getSid(),user);
				result.put("code", 1);
				result.put("msg", "操作成功");
			}else{
				result.put("code", 0);
				result.put("msg", "操作失败");
			}

		}catch(MdKnownRunTimeException e){
			result.put("code", 0);
			result.put("msg", e.getMessage());
			log.error(this, e);
		}catch (Exception e) {
			log.error(this, e);
			result.put("code", 0);
			result.put("msg", "操作失败");
		}
		return json;
	}

	/**
	 * 智能门禁发货
	 *
	 * @param agtCode     合作方				agtCode或communityId其中一个不能为空
	 * @param communityId 小区id
	 * @param sIds        sId集合 用,分割		非空
	 * @param user        当前用户
	 * @param userRole    当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/16 上午11:49
	 * @see TLocksServiceImpl#sendToTagentMethod(String, String, String, Sysopt, int)
	 */
	@Override
	public JSONObject sendToAgent(String agtCode, String communityId, String sIds, Sysopt user, int userRole) {

		JSONObject json = new JSONObject();

		//合作方和小区不能同时为空
		if(StringUtils.isBlank(agtCode) && StringUtils.isBlank(communityId)  ){
			json.put("code", 0);
			json.put("msg", "请选择要发货的公司或者社区");
//			json.put("data",sIds);
			return json;
		}
		//如果不传agtCoe则默认当前用户所在agtCode
		if (StringUtils.isBlank(agtCode)) {
			agtCode = user.getAgtCode();
		}

		//检验合作方是否有指定APP
		List<AppStoreEntity> appStoreList = appStoreDao.getListByAgtCode(agtCode);
		if(appStoreList.size()<1){
			json.put("code", "0");
			json.put("msg", "该未合作方还未指定APP,请添加应用");
			return json;
		}

		try {
			String pids_ = getPids(sIds);
			json.put("data", pids_);
			result.put("objectId", pids_);
			if (StringUtils.isBlank(pids_)) {
				json.put("code", 0);
				json.put("msg", "pid为空！");
				return json;
			}
			//发货
			Map<String,Object> result = sendToTaget(agtCode,communityId, pids_,user, userRole);
			json.putAll(result);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("硬件分配失败", e);
			json.put("code", 0);
			json.put("msg", "操作失败");
			throw new MdKnownRunTimeException("硬件分配失败");
		}
		return json;
	}

	/**
	 * 智能门禁批量发货
	 *
	 * @param agtCode     合作方				agtCode或communityId其中一个不能为空
	 * @param communityId 小区id
	 * @param pIdBegin    pId初始值
	 * @param pIdEnd      pId结束值
	 * @param user        当前用户
	 * @param userRole    当前用户userRole
	 * @see TLocksServiceImpl#sendToBatchTagentMethod
	 * @return
	 * @author Saber
	 * @Date 2017/8/16 下午1:40
	 */
	@Override
	public JSONObject sendToBatchTagent(String agtCode, String communityId, String pIdBegin, String pIdEnd, Sysopt user, int userRole) {

		JSONObject json = new JSONObject();

		//合作方和小区不能同时为空
		if(StringUtils.isBlank(agtCode) && StringUtils.isBlank(communityId)  ){
			json.put("code", 0);
			json.put("msg", "请选择要发货的公司或者社区");
			return json;
		}
		if (StringUtils.isBlank(pIdBegin) || StringUtils.isBlank(pIdEnd) ) {
			json.put("code", 0);
			json.put("msg", "请输入pid初始值和默认值");
			return json;
		}
		//如果不传agtCoe则默认当前用户所在agtCode
		if (StringUtils.isBlank(agtCode)) {
			agtCode = user.getAgtCode();
		}

		//检验合作方是否有指定APP
		List<AppStoreEntity> appStoreList = appStoreDao.getListByAgtCode(agtCode);
		if(appStoreList.size()<1){
			json.put("code", "0");
			json.put("msg", "该未合作方还未指定APP,请添加应用");
			return json;
		}

		try {
			String pIds = tLocksDao.getPidsByPidBeginAndPidEnd(agtCode,communityId,pIdBegin,pIdEnd);
			json.put("objectId", pIds);
			if (org.apache.commons.lang3.StringUtils.isEmpty(pIds)) {
				json.put("code", "0");
				json.put("msg", "找不到匹配的pid,无法分配");
				return json;
			}
			pIds = pIds.substring(0,pIds.length()-1);

			json.put("data",pIds);
			json.put("objectId", pIds);
			//发货
			Map<String,Object> result = sendToTaget(agtCode,communityId, pIds,user,userRole);//todo Updated by Saber on 2017/7/27 上午11:35
			json.putAll(result);
		} catch (Exception e) {
			log.error("硬件分配失败", e);
			json.put("code", 0);
			json.put("msg", "操作失败");
			throw new MdKnownRunTimeException("硬件分配失败");
		}

		return json;
	}

	/**
	 * 硬件检测（是否合格）
	 *
	 * @param ids      sId集合 用,分割
	 * @param type     检验状态,0:未检测，1：检查通过，2检查不通过
	 * @param user     当前用户
	 * @param userRole 当前用户userRole
	 * @see TLocksServiceImpl#checkMethod(String, String)
	 * @return
	 * @author Saber
	 * @Date 2017/8/21 下午1:13
	 */
	@Override
	public JSONObject check(String ids, String type, Sysopt user, int userRole) {
		JSONObject json = new JSONObject();

		try {
			json.put("objectId", ids);
//			List<Long> ids = new LinkedList<Long>();
			for (String sId : ids.split(",")) {
				TLocksEntity tlock = tLocksDao.selectByPrimaryKey(Long.parseLong(sId));
				tlock.setCheckstatus(type);

//            	update(tlock);
				tLocksDao.updateByPrimaryKeySelective(tlock);
			}

			json.put("code", 1);
			json.put("msg", "操作成功");
			json.put("data",ids);
			return json;
		} catch (Exception e) {
			log.error("硬件修改状态失败", e);
			json.put("code", 0);
			json.put("msg", "硬件修改状态失败");
			return json;
		}
	}

	/**
	 * 硬件新增保存
	 *
	 * @param pId             pId
	 * @param checkCode       激活码
	 * @param installLockName 门禁名称
	 * @param user            当前用户
	 * @param userRole        当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/21 下午1:54
	 * @see com.eportal.action.background.TLocksAction#add()
	 * @see TLocksServiceImpl#addMethod(TLock, String, Sysopt)
	 */
	@Override
	public JSONObject add(String pId, String checkCode, String installLockName, Sysopt user, int userRole) {

		JSONObject json = new JSONObject();

		try {

			if(StringUtils.isBlank(pId)){
				json.put("code", 0);
				json.put("msg", "pid不能为空，请输入");
				return json;
			}
			if(StringUtils.isBlank(checkCode)){
				json.put("code", 0);
				json.put("msg", "激活码不能为空，请输入");
				return json;
			}

			//根据pid查询对象
			TLocksEntity entity =tLocksDao.getByPid(pId);

			if(entity == null){
				json.put("code", 0);
				json.put("msg", "查询不到此pid，请检查后重新输入");
				return json;
			}
			if(!"1".equals(entity.getCheckstatus())){
				json.put("code", 0);
				json.put("msg", "该硬件未检测或检查不通过，无法安装");
				return json;
			}
			if(StringUtils.isBlank(entity.getCheckcode())){
				json.put("code", 0);
				json.put("msg", "锁的激活码不存在，请联系锁厂解决");
				return json;
			}
			if(!entity.getCheckcode().equals(checkCode)){
				json.put("code", 0);
				json.put("msg", "锁的校验码不匹配，请检查后请重新输入");
				return json;
			}
			if(!user.getAgtCode().equals(entity.getAgtcode())){
				json.put("code", 0);
				json.put("msg", "智能锁状态不符合安装要求，请联系商家");
				return json;
			}

			//激活码
			entity.setCheckcode(checkCode);
			//如果门禁名称为空 则使用 pId 做门禁名称
			if(StringUtils.isNotBlank(installLockName)){
				entity.setInstallLockName(installLockName);
			}else{
				entity.setInstallLockName(pId);
			}
			//接口安装锁

			TCommunityEntity tCommunity =tCommunityDao.getByTypeAndId(2,Long.valueOf(user.getCommunityId()));
			if(tCommunity == null){
				json.put("code", 0);
				json.put("msg", "查不到安装硬件到客户信息，请用锁厂客户身份登录");
				return json;
			}
			entity.setStatus("1");
			entity.setCommunityid(Long.toString(tCommunity.getSid()));
			entity.setInstallTime(new Timestamp(System.currentTimeMillis()));

			//自动安装锁	todo 运行测试类时请注释本行 Created by Saber on 2017/8/21 下午4:01
			json = installLockMy(tCommunity, entity);
			if (!"1".equals(json.get("code").toString())) {
				throw new MdKnownRunTimeException(json.get("msg").toString());
			}
			tLocksDao.updateByPrimaryKeySelective(entity);

			json.put("objectId", entity.getSid());
			json.put("code", 1);
			json.put("msg", "操作成功");
			json.put("data", entity.getSid());

			return json;
		}catch (MdKnownRunTimeException e) {
			log.error("硬件保存失败", e);
			json.put("code", 0);
			json.put("msg", e.getMessage());
			return json;
		}catch (Exception e) {
			log.error("硬件保存失败", e);
			json.put("code", 0);
			json.put("msg", "操作失败");
			return json;
		}
	}

	/**
	 * 导出激活码（获取要导出的数据）
	 *
	 * @param pIdBegin pId初始值
	 * @param pIdEnd   pIdJ结束值
	 * @param user     当前用户
	 * @param userRole 当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/21 下午4:38
	 * @see TLocksAction#export()
	 */
	@Override
	public List<TLocksEntity> getByPidAndAgtCodeForExport(String pIdBegin, String pIdEnd, Sysopt user, int userRole) {

		return tLocksDao.getByPidAndAgtCodeForExport(pIdBegin,pIdEnd,user,userRole);
	}
}
